//
//  VideoModel.m
//  SmartiOSPublisher
//
//  Created by Liu,Qingcan on 2017/4/25.
//  Copyright © 2017年 Baidu. All rights reserved.
//

#import "VideoModel.h"

@implementation VideoModel


- (void)insertVideoData:(LEVideoRoom *)item{
    PersistenceCommon *common = [PersistenceCommon shareInstance];
    //创建需要保存的对象personOne
    
        Video *One = [NSEntityDescription insertNewObjectForEntityForName:@"Video"inManagedObjectContext:common.currentContext];
    
        //设置personOne的属性，这里personOne和我们平常用的person实例有一点区别，它无法通过点语法直接拿到属性（后面有解决方法），只能通过KVC来设置它的属性
    
        One.nid = item.nid;
        One.title = item.title;
        One.round_name = item.round_name;
        One.round_url = item.round_url;
        One.round_start_time = item.round_start_time;
        One.round_start_time = item.round_start_time;
        One.round_status = item.round_status;
        One.video_room_id = item.video_room_id;
    
    // 利用上下文对象，将数据同步到持久化存储库
    NSError *errors = nil;
    //保存数据
    BOOL success =[common.currentContext save:&errors];
    
    if (!success) {
        [NSException raise:@"数据库访问错误" format:@"%@",[errors localizedDescription]];
    }
    
    
}

- (NSArray *)selectVideos:(NSInteger)roomId{
//    NSMutableArray *result = [NSMutableArray array];
    
    //得到要查询的表
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Video" inManagedObjectContext:self.persistence.currentContext];
    //建立查询的工具类
    NSFetchRequest *req = [[NSFetchRequest alloc]init];
    [req setEntity:entity];
    //谓词
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"video_room_id = %d",roomId];
    [req setPredicate:predicate];
    
    //结果
    NSError *error = nil;
    NSArray *array = [self.persistence.currentContext executeFetchRequest:req error:&error];
    
    
    
    return array;
}




/**
 * number 是起始数字
 */
- (NSArray *)selectNumberOfData:(NSInteger)number{
    NSMutableArray *result = [NSMutableArray array];
    
    //    PersistenceCommon *common = [PersistenceCommon shareInstance];
    // 初始化一个查询请求
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    // 设置要查询的实体
    request.entity = [NSEntityDescription entityForName:@"Video" inManagedObjectContext:self.persistence.currentContext];
    // 设置排序（按照id降序）
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"id" ascending:NO];
    request.sortDescriptors = [NSArray arrayWithObject:sort];
    // 设置条件过滤(搜索name中包含字符串"Itcast-1"的记录，注意：设置条件过滤时，数据库SQL语句中的%要用*来代替，所以%Itcast-1%应该写成*Itcast-1*)
    //        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like %@", @"*Itcast-1*"];
    //        request.predicate = predicate;
    // 执行请求
    NSError *error = nil;
    NSArray *objs = [self.persistence.currentContext executeFetchRequest:request error:&error];
    if (error) {
        [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
    }
    int endFlag = 0;
    int countNumber = objs.count-10;
    if ( countNumber>= number) {
        endFlag = objs.count;
    }else{
        if(objs.count >= number){
            endFlag = objs.count - number;
        }else{
            return result;
        }
        
    }
    
    // 遍历数据
    for (int index = 0; index < endFlag; index ++) {
        
        Video *item = objs[index+number];
        LEVideoRoom *One = [LEVideoRoom new];
        One.nid = item.nid;
        One.title = item.title;
        One.round_name = item.round_name;
        One.round_url = item.round_url;
        One.round_start_time = item.round_start_time;
        One.round_start_time = item.round_start_time;
        One.round_status = item.round_status;
        One.video_room_id = item.video_room_id;
        [result addObject:One];
    }
    
    //    for (Video *obj in objs) {
    //
    //
    //        NSLog(@"name=%@", [obj valueForKey:@"Videoname"] ) ;
    //        NSLog(@"pwd=%@", [obj valueForKey:@"Videopwd"] ) ;
    //    }
    
    
    
    return [result copy];
}


- (void)deleteVideo:(Video *)item{
    [self.persistence.currentContext deleteObject:item];
    // 将结果同步到数据库
    NSError *error = nil;
    [self.persistence.currentContext save:&error];
    if (error) {
        [NSException raise:@"删除错误" format:@"%@", [error localizedDescription]];
    }
}



- (void)updateVideo:(Video *)item{
    //得到要查询的表
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Video" inManagedObjectContext:self.persistence.currentContext];
    //建立查询的工具类
    NSFetchRequest *req = [[NSFetchRequest alloc]init];
    [req setEntity:entity];
    //谓词
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"nid = %d",item.nid];
    [req setPredicate:predicate];
    
    //结果
    NSError *error = nil;
    NSArray *array = [self.persistence.currentContext executeFetchRequest:req error:&error];
    
    
    //遍历结果集更改对象属性
    for (Video *One in array) {
        One.nid = item.nid;
        One.title = item.title;
        One.round_name = item.round_name;
        One.round_url = item.round_url;
        One.round_start_time = item.round_start_time;
        One.round_status = item.round_status;
        One.video_room_id = item.video_room_id;
    }
    [self deleteVideo:array.firstObject];
    
    //更新操作需要同步
    // 利用上下文对象，将数据同步到持久化存储库
    NSError *errors = nil;
    //保存数据
    BOOL success =[self.persistence.currentContext save:&errors];
    if (!success) {
        [NSException raise:@"数据库访问错误" format:@"%@",[errors localizedDescription]];
    }
    
}



- (void)deleteAllVideo{
    NSMutableArray *result = [NSMutableArray array];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    request.entity = [NSEntityDescription entityForName:@"Video" inManagedObjectContext:self.persistence.currentContext];
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"nid" ascending:NO];
    request.sortDescriptors = [NSArray arrayWithObject:sort];
    // 执行请求
    NSError *error = nil;
    NSArray *objs = [self.persistence.currentContext executeFetchRequest:request error:&error];
    if (error) {
        [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
    }
    
    // 遍历数据
    for (int index = 0; index < objs.count; index ++) {
        [result addObject:objs[index]];
    }
    for (Video *item in result) {
        [self.persistence.currentContext deleteObject:item];
    }
    
    // 将结果同步到数据库
    //    NSError *error = nil;
    [self.persistence.currentContext save:&error];
    if (error) {
        [NSException raise:@"删除错误" format:@"%@", [error localizedDescription]];
    }
    
}



- (PersistenceCommon *)persistence{
    if (!_persistence) {
        _persistence = [PersistenceCommon shareInstance];
    }
    return _persistence;
}


@end

